<?php
/**
 * 作者：云喵软件开发工作室
 * 官网：https://www.meoyun.com
 */

namespace app\api\controller;

use app\model\DiscussModel;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Validator as v;
use support\exception\BusinessException;
use support\Request;
use Throwable;
class Discuss extends BaseApi
{
    /** 绑定数据模型 */
    protected $dataModel = DiscussModel::class;

    /** 预加载关联 */
    protected array $with = ['user'];

    /** 允许搜索的字段 */
    protected array $allowSearch = ['title', 'user_id'];

    /** 搜索配置 */
    protected array $searchConfig = [
        'title' => ['type' => 'like'],
        'created_at' => ['type' => 'date_range'],
    ];

    /** 发布话题 */
    public function publish(Request $request): mixed
    {
        $userId = $this->getUserId();

        // 校验参数
        try {
            $params = v::input($request->all(), [
                'title' => v::stringType()->notEmpty()->length(6, 30)->setName('标题'),
                'content' => v::optional(v::stringType())->setName('内容'),
                'media' => v::optional(v::arrayType())->setName('媒体'),
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        try {
            $row = new DiscussModel();
            $row->user_id = $userId;
            $row->title = $params['title'];
            $row->content = $params['content'];
            $row->media = $params['media'];
            $row->save();

            return $this->success($row, '发布成功');
        } catch (Throwable $e) {
            throw new BusinessException('发布失败: ' . $e->getMessage(), 400, $e);
        }
    }

    /** 获取话题详情 */
    public function getInfo(Request $request): mixed
    {
        try {
            $params = v::input($request->all(), [
                'id' => v::stringType()->notEmpty()->setName('ID')
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        try {
            $query = $this->buildBaseQuery();
            $detail = $query->where('id', $params['id'])->firstOrFail();
            // 增加浏览量
            $detail->increment('view_count');

            return $this->success($detail);
        } catch (Throwable $e) {
            throw new BusinessException('获取详情失败: ' . $e->getMessage(), 400, $e);
        }
    }
}